package com.robot.member.controller;

import java.util.Map;

import com.robot.member.pojo.Member;
import com.robot.member.service.MemberService;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import com.robot.member.pojo.Feedback;
import com.robot.member.service.FeedbackService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import util.CheckUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * feedback控制器层
 *
 * @author
 */
@RestController
@CrossOrigin
@RequestMapping("/feedback")
public class FeedbackController {
    @Autowired
    private FeedbackService feedbackService;
    @Autowired
    private MemberService memberService;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CheckUtil checkUtil;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(StatusCode.SUCCESS_QUERY, feedbackService.findAll());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "admin/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(StatusCode.SUCCESS_QUERY, feedbackService.findById(id));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<Feedback> pageList = feedbackService.findSearch(searchMap, page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<Feedback>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(StatusCode.SUCCESS_QUERY, feedbackService.findSearch(searchMap));
    }

    /**
     * 增加
     *
     * @param feedback
     */
    @PostMapping
    public Result add(@RequestBody Feedback feedback) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        logger.info("feedback=" + feedback);
        if (feedback.getContent() == null || "".equals(feedback.getContent())) {
            return new Result(StatusCode.ERROR_CONTENT_REQUIRED);
        }
        if (feedback.getPhone() == null || "".equals(feedback.getPhone()) || !checkUtil.checkPhone(feedback.getPhone())) {
//            return new Result(StatusCode.ERROR_INVALID_PHONE);
        }
        Member memberInDb = memberService.findById(claims.getId());
        logger.info("memberInDb=" + memberInDb);
        if (memberInDb != null && memberInDb.getOpenId() != null) {
            feedback.setOpenId(memberInDb.getOpenId());
        }

        feedback.setMemberId(claims.getId());
        feedbackService.add(feedback);
        return new Result(StatusCode.SUCCESS, "感谢你的反馈");
    }

    /**
     * 根据memberId查会员的所有反馈并分页
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("{page}/{size}")
    public Result findAllByMemberIdOrderByCreatedAt(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Page<Feedback> pageData = feedbackService.findAllByMemberIdOrderByCreatedAt(claims.getId(), page, size);
        logger.info("feedback pageData=" + pageData);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));
    }

    /**
     * 根据id和memberId查会员的某一反馈详情
     *
     * @param id ID
     * @return
     */
    @GetMapping("{id}")
    public Result findByIdAndMemberId(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Feedback feedbackInDb = feedbackService.findByIdAndMemberId(id, claims.getId());
        logger.info("feedbackInDb=" + feedbackInDb);
        if (feedbackInDb == null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        return new Result(StatusCode.SUCCESS_QUERY, feedbackInDb);
    }

    /**
     * 修改
     *
     * @param feedback
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody Feedback feedback, @PathVariable String id) {
        feedback.setId(id);
        feedbackService.update(feedback);
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id) {
        feedbackService.deleteById(id);
        return new Result(StatusCode.SUCCESS_DELETED);
    }
}
